// pages/zone/zone.js
var app = getApp()
let utils = require("../../utils/util.js")

const Toast = require('../../dist/toast/toast');
Page({
  data: {
    popsBar: false,
    isShow: true,
    iscamera: false,
    imgName: [],
    actions: [{
      name: '从相册中选择',
      loading: false
    }
    // {
    //   name: '拍照',
    //   loading: false
    // }
    ],
    cancelText: '关闭',
    imagePath: [],
    src: '../../images/add.png',
    said: ''
  },
  onLoad() {
    this.ctx = wx.createCameraContext()
    console.log('onLoad')
  },
  joinPicture() {
    this.setData({
      popsBar: !this.data.popsBar
    });
  },
  closeActionSheet() {
    this.setData({
      popsBar: !this.data.popsBar
    });
  },
  handleActionClick({ detail }) {
    // 获取被点击的按钮 index
    const { index } = detail;
    if (!index) {
      var that = this;
      wx.chooseImage({
        count: 4, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths
          // console.error(res.tempFiles)
          for (let i in res.tempFiles){
            console.log(res.tempFiles[i].size)
            if (res.tempFiles[i].size < (1024 * 500)) {
              that.setData({
                imagePath: res.tempFilePaths
              })
            } else {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: '图片不能超过 500KB'
              })
            }
          }
          
          that.setData({
            popsBar: false
          });
          if (that.data.imagePath.length === 4) {
            that.setData({
              isShow: !that.data.isShow
            });
          }
        }
      })
    } else {
      this.setData({
        iscamera: true,
        popsBar: false
      })
    }
  },
  takePhoto() {
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          iscamera: false,
          popsBar: false
        })
      }
    })
  },
  submitClick(val) {  // 发布
    let pathList = this.data.imagePath
    this.uploadServer({
      url: app.ipaddress +'uploadqiniu',
      path: pathList,
      imagenames: []
    })
  },
  uploadServer(data) {
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
      },
      success: (resp) => {
        success++;
        console.log("success", resp)
        var dataJson = JSON.parse(resp.data)
        data.imagenames.push(dataJson.imagename);
      },
      fail: (res) => {
        fail++;
        console.log(res)
      },
      complete: () => {
        i++;
        if (i == data.path.length) {   //当图片传完时，停止调用

          wx.showToast({
            title: '上传成功',
            duration: 1500,
            mask: 'false'
          })
          that.setData({
            tempFilePaths: [],
            imgName: data.imagenames
          })
          let imageList = '';
          if (this.data.imgName.length) {
            imageList = this.data.imgName.join(',')
          } else {
            imageList = this.data.src
          }
          utils.getData('uploadData', {
            "circleSaid": this.data.said,
            "imageList": imageList,
            "userId": app.userId
          }, "POST").then(res => {
            console.log(res)
            if (res.data.success){
              wx.reLaunch({
                url: '../chat/chat'
              })
            }else{
              Toast({
                message: '处理失败，请稍后再试!',
                selector: '#zan-toast-test'
              });
            }
          
          })
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadServer(data);
        }
      }
    })
  },
  getSaid: function (e) {
    this.setData({
      said: e.detail.value
    })
  },
  error(e) {
    console.log(e)
  }
})